/**
 * 
 */
package com.richapp.launcher.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.jack.netty.log.LoggerManager;
import com.jack.util.date.DateUtil;
import com.richapp.launcher.R;
import com.richapp.launcher.control.PageControl;


/**
 * 预装APK管理工具类
 * @author zengjiantao
 */
public class ApkUtil {

	/** appType:未知软件类型 */
	public static final int UNKNOW_APP = 0;

	/** appType:用户软件类型 */
	public static final int USER_APP = 1;

	/** appType:系统软件 */
	public static final int SYSTEM_APP = 2;

	/** appType:系统升级软件 */
	public static final int SYSTEM_UPDATE_APP = 4;

	/** appType:系统+升级软件 */
	public static final int SYSTEM_REF_APP = SYSTEM_APP | SYSTEM_UPDATE_APP;

	/**
	 * 检查app是否是系统rom集成的
	 * 
	 * @param pname
	 * @return
	 */
	public static int checkAppType(Context context, String pname) {
		try {
			// PackageManager.GET_META_DATA
			PackageInfo pInfo = context.getPackageManager().getPackageInfo(
					pname, PackageManager.GET_META_DATA);

			// 是系统软件或者是系统软件更新
			if (isSystemApp(pInfo) || isSystemUpdateApp(pInfo)) {
				return SYSTEM_REF_APP;
			} else {
				return USER_APP;
			}

		} catch (NameNotFoundException e) {
			Log.v("error", e.getMessage());
		}

		return UNKNOW_APP;
	}

	/**
	 * 是否是系统软件
	 * 
	 * @param pInfo
	 * @return
	 */
	private static boolean isSystemApp(PackageInfo pInfo) {
		return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
	}

	/**
	 * 是否是系统软件的更新软件
	 * 
	 * @param pInfo
	 * @return
	 */
	private static boolean isSystemUpdateApp(PackageInfo pInfo) {
		return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
	}

	/**
	 * 安装Apk
	 * 
	 * @param context
	 */
	public static void install(Context context, final String filePath) {
		// 检查系统是否允许安装第三方应用
		if (isInstallingUnknownAppsAllowed(context)) {
			installApk(context, filePath);
		} else {
			Toast.makeText(context, R.string.no_allow_install,Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 安装Apk
	 * 
	 * @param context
	 */
	public static void installApk(Context context, String filePath) {
		Intent installer = new Intent(Intent.ACTION_VIEW);
		installer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// Uri.fromFile(new File(filePath))
		installer.setDataAndType(Uri.parse("file://" + filePath),
				"application/vnd.android.package-archive");
		try {
			context.startActivity(installer);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, R.string.install_fail,
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 是否允许安装第三方应用
	 * 
	 * @return
	 */
	public static boolean isInstallingUnknownAppsAllowed(Context context) {
		return Settings.Secure.getInt(context.getContentResolver(),
				Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;
	}

	/**
	 * 静默安装Apk，应用需要权限
	 * 
	 * @param context
	 * @param file
	 */
	public static void installApkSilent(final Context context, String packageName,File file) {
		try {
			Class packageManage = Class.forName("android.content.pm.PackageManager");

			Class packageInstallObserver = Class.forName("android.content.pm.IPackageInstallObserver");

			Method installPackage = packageManage.getMethod("installPackage",Uri.class, packageInstallObserver, int.class, String.class);

			int INSTALL_REPLACE_EXISTING = packageManage.getField("INSTALL_REPLACE_EXISTING").getInt(null);

			Object iActivityManager = installPackage.invoke(context.getPackageManager(), Uri.fromFile(file), null, INSTALL_REPLACE_EXISTING, packageName);

		} catch (Exception e) {
			LoggerManager.getInstance().getiLogger().error(ApkUtil.class, "静默安装失败:" + e.getMessage());
			Toast toast = Toast.makeText(context, "静默安装失败!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}


	public static void installSlient(Context context, File apkFile) {
		if(apkFile == null || !apkFile.exists()){
			LoggerManager.getInstance().getiLogger().error(ApkUtil.class, "安装文件丢失");
			Toast toast = Toast.makeText(context, "安装文件丢失!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			return ;
		}

		String[] args = { "pm", "install", "-r", apkFile.getAbsolutePath() };
		ProcessBuilder processBuilder = new ProcessBuilder(args);

		Process process = null;
		BufferedReader successResult = null;
		BufferedReader errorResult = null;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder errorMsg = new StringBuilder();
		try {
			process = processBuilder.start();
			successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
			errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String s;

			while ((s = successResult.readLine()) != null) {
				successMsg.append(s);
			}

			while ((s = errorResult.readLine()) != null) {
				errorMsg.append(s);
			}
		} catch (Exception e) {
			LoggerManager.getInstance().getiLogger().error(ApkUtil.class, "静默安装失败:" + e.getMessage());
			Toast toast = Toast.makeText(context, "静默安装失败!", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} finally {
			try {
				if (successResult != null) {
					successResult.close();
				}
				if (errorResult != null) {
					errorResult.close();
				}
			} catch (IOException e) {
				LoggerManager.getInstance().getiLogger().error(ApkUtil.class, "静默安装错误:" + e.getMessage());
			}
			if (process != null) {
				process.destroy();
			}
		}
	}

	/**
	 * 判断系统是否存在该应用
	 * 
	 * @param context
	 * @param packName
	 * @return
	 */
	public static boolean isExistApp(Context context, String packName) {
		List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
		for (int i = 0; i < packages.size(); i++) {
			PackageInfo packageInfo = packages.get(i);
			if (packageInfo.packageName.equals(packName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取本地版本字符串(AndroidManifest.xml中配置的版本信息)
	 * 
	 * @return
	 */
	public static String getLocalVersion(Context context) {
		PackageManager pm = context.getPackageManager();
		String version = null;
		try {
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			version = pi.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 获取本地版本字符串(AndroidManifest.xml中配置的版本信息)
	 * 
	 * @return
	 */
	public static int getLocalVersionCode(Context context) {
		PackageManager pm = context.getPackageManager();
		int versionCode = Integer.MIN_VALUE;
		try {
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionCode = pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取已安装apk的版本编号
	 * 
	 * @return
	 */
	public static int getInstallVersionCode(Context context, String pkgName) {
		PackageManager pm = context.getPackageManager();
		int versionCode = Integer.MIN_VALUE;
		try {
			PackageInfo pi = pm.getPackageInfo(pkgName,
					PackageManager.GET_ACTIVITIES);
			versionCode = pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取未安装apk的版本编号
	 */
	public static int getUninstallVersionCode(Context context,
			String archiveFilePath) {
		PackageManager pm = context.getPackageManager();
		PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath,
				PackageManager.GET_ACTIVITIES);
		if (info != null) {
			ApplicationInfo appInfo = info.applicationInfo;
			String appName = pm.getApplicationLabel(appInfo).toString();
			String packageName = appInfo.packageName; // 得到安装包名称
			String version = info.versionName; // 得到版本信息
			int versionCode = info.versionCode;
			return versionCode;
		}
		return Integer.MIN_VALUE;
	}

	/**
	 * 获得属于桌面的应用的应用包名称
	 * 
	 * @return 返回包含所有包名的字符串列表
	 */
	public static List<String> getHomes(Context context) {
		List<String> names = new ArrayList<String>();
		PackageManager packageManager = context.getPackageManager();
		// 属性
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
				intent, PackageManager.MATCH_DEFAULT_ONLY);
		for (ResolveInfo ri : resolveInfo) {
			names.add(ri.activityInfo.packageName);
			Log.v("info",ri.activityInfo.packageName);
		}
		return names;
	}

	/**
	 * 判断当前应用是否是home
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isHome(Context context) {
		String packageName = context.getPackageName();
		List<String> homePackageNames = getHomes(context);
		if (Toolkit.isEmpty(homePackageNames)) {
			return false;
		} else {
			return homePackageNames.contains(packageName);
		}
	}

	/**
	 * 判断当前界面是否是桌面
	 */
	public static boolean isInHome(Context context) {
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		List<String> homePackageNames = getHomes(context);
		if (Toolkit.isEmpty(homePackageNames)) {
			return false;
		} else {
			return homePackageNames.contains(rti.get(0).topActivity
					.getPackageName());
		}
	}

}
